package com.mvvm.start.main.mvvm.v.activity

import android.Manifest
import android.annotation.SuppressLint
import android.app.Application
import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.view.KeyEvent
import android.view.MenuItem
import android.view.View
import androidx.annotation.RequiresApi
import androidx.fragment.app.Fragment
import androidx.viewpager2.widget.ViewPager2
import com.alibaba.android.arouter.facade.annotation.Route
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.mvvm.start.base.BaseApplication
import com.mvvm.start.base.base.BaseActivity
import com.mvvm.start.base.utils.*
import com.mvvm.start.main.R
import com.mvvm.start.common.constant.RouteUrl
import com.mvvm.start.common.mvvm.v.dialog.UpDataProgressDialog
import com.mvvm.start.common.mvvm.v.dialog.UpdataAppTipsDialog
import com.mvvm.start.common.utils.FileUtils
import com.mvvm.start.common.utils.PermissionXUtils
import com.mvvm.start.common.utils.UpDateAppHelper
import com.mvvm.start.main.databinding.ActivityMainBinding
import com.mvvm.start.main.mvvm.v.adapter.BottomAdapter
import com.mvvm.start.main.mvvm.v.fragment.main.HelpFragment
import com.mvvm.start.main.mvvm.v.fragment.main.HomeFragment
import com.mvvm.start.main.mvvm.v.fragment.main.MarketFragment
import com.mvvm.start.main.mvvm.v.fragment.main.MineFragment
import com.mvvm.start.main.mvvm.vm.MainViewModle
import java.io.File


/**
 * @author lmy
 * @功能: 主界面 使用框架之前一定要修改MVVMStartGsonConverterFactory逻辑
 * @Creat 12/11/20 4:14 PM
 * @Compony 465008238@qq.com
 */
@Route(path = RouteUrl.CommonMainActivity)
class MainActivity : BaseActivity<MainViewModle, ActivityMainBinding>() {
    val fragments = mutableListOf<Fragment>(
        HomeFragment(),
        MarketFragment(),
        HelpFragment(),
        MineFragment()
    )
    private val updataDialog: UpdataAppTipsDialog by lazy { UpdataAppTipsDialog(this@MainActivity) }
    private val upDataProgressDialog: UpDataProgressDialog by lazy { UpDataProgressDialog(this@MainActivity) }
    @SuppressLint("WrongConstant")
    override fun initView() {
//        initNetReceiver()
        initEasyNavigationBar()
        PermissionXUtils.requestPermissions(
            this@MainActivity,
            mutableListOf(
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            ), {
                "权限获取成功".loge()
            }, {
                "拒绝存储权限会导致软件更新无法使用".toast()
            }, "检查更新需要存储权限 您需要开启才可使用该功能"
        )
    }


    /**
     * 初始化底部导航栏
     */
    @SuppressLint("WrongConstant")
    private fun initEasyNavigationBar() {
        viewBinding.apply {

            navigationBtView.labelVisibilityMode = 1
            navigationBtView.itemIconTintList = null
            navigationBtView.setOnNavigationItemSelectedListener(object :
                BottomNavigationView.OnNavigationItemSelectedListener {
                override fun onNavigationItemSelected(item: MenuItem): Boolean {
                    when (item.itemId) {
                        R.id.home -> {
                            //这里切换的时候会从1到4的时候会逐渐过来 调用此方法禁止此效果
                            viewpager.setCurrentItem(0, false)
                            return true
                        }
                        R.id.market -> {
                            viewpager.setCurrentItem(1, false)
                            return true
                        }
                        R.id.help -> {
                            viewpager.setCurrentItem(2, false)
                            return true
                        }
                        R.id.mine -> {
                            viewpager.setCurrentItem(3, false)
                            return true
                        }
                    }
                    return false
                }
            })
            viewpager.adapter = BottomAdapter(supportFragmentManager, lifecycle, fragments)
            viewpager.offscreenPageLimit = 3
            viewpager.isUserInputEnabled = false//是否禁止滑动
            viewpager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
                override fun onPageSelected(position: Int) {
                    /**
                     * 这里监听ViewPager的滑动
                     * 动态改变状态栏的颜色 适配沉浸式状态栏
                     */
                    if (NavigationBar.checkDeviceHasNavigationBar(this@MainActivity)) {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                            window.navigationBarColor = Color.parseColor("#ffffff")
                            //设置状态栏
                            if (position == 3) {
                                window.decorView.systemUiVisibility =
                                    View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or
                                            View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR or
                                            View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR
                            } else {
                                window.decorView.systemUiVisibility =
                                    View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or
//                                        View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR or
                                            View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR
                            }
                        }
                    }
                    navigationBtView.menu.getItem(position).isChecked = true
                    if (position == 1) {
                        (fragments[1] as MarketFragment).initData()
                    }
                }
            })
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        //拦截返回键 处理两次返回间隔事件确认是否退出
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return if (System.currentTimeMillis() - mViewModel.exitTipTime <= 2000) {
                // 由于是在入口 Activity 中，我们交给 super，它会帮我们退出。
                var intent = Intent(Intent.ACTION_MAIN);
                intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP;
                intent.addCategory(Intent.CATEGORY_HOME);
                startActivity(intent);
                true
            } else {
                mViewModel.exitTipTime = System.currentTimeMillis()
                "再按一次返回到桌面".toast()
                true
            }
        }
        return super.onKeyDown(keyCode, event)
    }


    override fun initObserve() {
        mViewModel.apply {
        }
    }

    override fun onResume() {
        super.onResume()
        initUpdata()
    }

    override fun initData() {

    }

    @RequiresApi(api = Build.VERSION_CODES.M)  //处理回调
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        for (fragment in fragments) {
            fragment.onActivityResult(requestCode, resultCode, data)
        }
    }

    private fun initUpdata() {
        if (ConstantUtils.isSkipUpdaApp) {
            return
        }
        if (upDataProgressDialog.isShowing) {
            return
        }
        if (updataDialog.isShowing) {
            return
        }
        CommonUtils.getPublicConfig()?.updata?.apply {
            if (versionNum > CommonUtils.getAppVersionCode()) {
                var mAppPath = "${BaseApplication.context.getExternalFilesDir(null)}${File.separator}Download${File.separator}点猫v:${versionName}.apk"
                updataDialog.apply {
                    setCancelable(false)
                    if (FileUtils.isFileExists(File(mAppPath))) {
                        defaltbinding.tvCancel.visibility = View.VISIBLE
                    } else {
                        if (forceUpdataType == 1) {
                            defaltbinding.tvCancel.visibility = View.GONE
                        }
                    }
                    setDefaltBean {
                        defaltBean.apply {
                            title = "新版本V:${versionName}"
                            sure = if (FileUtils.isFileExists(File(mAppPath))) "立即安装" else "立即下载"
                            cance = if (FileUtils.isFileExists(File(mAppPath))) "重新下载" else "下次再说"
                            message = info
                        }
                    }
                    setCancelAndSureClick({
                        if (defaltbinding.tvCancel.text.equals("重新下载")) {
                            PermissionXUtils.requestPermissions(this@MainActivity,
                                mutableListOf(Manifest.permission.READ_EXTERNAL_STORAGE,
                                    Manifest.permission.WRITE_EXTERNAL_STORAGE),
                                {
                                    showUpDataProgressDialog(versionName, downUrl)
                                    dismiss()
                                },
                                {
                                    "拒绝存储权限会导致软件更新无法使用".toast()
                                },
                                "检查更新需要存储权限 您需要开启才可使用该功能")
                        } else {
                            ConstantUtils.isSkipUpdaApp = true
                            dismiss()
                        }
                    }) {
                        if (FileUtils.isFileExists(File(mAppPath))) {
                            UpDateAppHelper.installAPK(this@MainActivity, File(mAppPath))
                            return@setCancelAndSureClick
                        }
                        PermissionXUtils.requestPermissions(this@MainActivity,
                            mutableListOf(Manifest.permission.READ_EXTERNAL_STORAGE,
                                Manifest.permission.WRITE_EXTERNAL_STORAGE),
                            {
                                showUpDataProgressDialog(versionName, downUrl)
                                dismiss()
                            },
                            {
                                "拒绝存储权限会导致软件更新无法使用".toast()
                            },
                            "检查更新需要存储权限 您需要开启才可使用该功能")

                    }
                }.show()
            }
        }

    }

    private fun showUpDataProgressDialog(versionName: String, downUrl: String) {
        upDataProgressDialog.apply {
            setTitle("升级到v${versionName}版本")
            setDialogCancelable(false) //设置禁止取消下载进度条
        }
        upDataProgressDialog.show()
        UpDateAppHelper.updateApp(downUrl, true, "点猫v:${versionName}.apk", {
            upDataProgressDialog.setProgress(it)
        }, { upDataProgressDialog.dismiss() }) {
            "下载失败:$it".toast()
            upDataProgressDialog.dismiss()
            initUpdata()

        }
    }

}